package com.zc.manager.notify.service.impl;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.zc.component.gateway.annotation.Subscribe;
import com.ruoyi.common.utils.DateUtils;
import com.zc.component.notify.core.event.SerializableNotifierEvent;
import org.springframework.stereotype.Service;
import com.zc.manager.notify.mapper.NotifyHistoryMapper;
import com.zc.manager.notify.domain.NotifyHistory;
import com.zc.manager.notify.service.NotifyHistoryService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
/**
 * 通知记录Service业务层处理
 *
 * @author wangjiabao
 * @date 2022-11-14
 */
@Service
public class NotifyHistoryServiceImpl implements NotifyHistoryService {
    @Resource
    private NotifyHistoryMapper notifyHistoryMapper;

    /**
     * 查询通知记录
     *
     * @param id 通知记录主键
     * @return 通知记录
     */
    @Override
    public NotifyHistory selectNotifyHistoryById(Long id) {
        return notifyHistoryMapper.selectNotifyHistoryById(id);
    }

    /**
     * 查询通知记录列表
     *
     * @param notifyHistory 通知记录
     * @return 通知记录
     */
    @Override
    public List<NotifyHistory> selectNotifyHistoryList(NotifyHistory notifyHistory) {
        return notifyHistoryMapper.selectNotifyHistoryList(notifyHistory);
    }

    /**
     * 新增通知记录
     *
     * @param notifyHistory 通知记录
     * @return 结果
     */
    @Override
    public int insertNotifyHistory(NotifyHistory notifyHistory) {
        notifyHistory.setCreateTime(DateUtils.getNowDate());
        return notifyHistoryMapper.insertNotifyHistory(notifyHistory);
    }

    @Subscribe("/notify/**")
    @Transactional(propagation = Propagation.NEVER)
    public Mono<Void> handleNotify(SerializableNotifierEvent event) {
        NotifyHistory history = new NotifyHistory();
        history.setTemplate(JSONObject.toJSONString(event.getTemplate()));
        history.setContext(event.getContext().toString());
        history.setErrorType(event.getErrorType());
        history.setNotifyType(event.getNotifyType());
        history.setNotifierId(Long.valueOf(event.getNotifierId()));
        history.setProvider(event.getProvider());
        history.setErrorStack(event.getCause());
        history.setRetryTimes(Long.valueOf(0));
        if (!StringUtils.isEmpty(event.getTemplateId())){
            history.setTemplateId(Long.valueOf(event.getTemplateId()));
        }
        if (event.isSuccess()){
            //说明发送成功
            history.setState("success");
        }else {
            history.setState("error");
        }
        history.setNotifyTime(DateUtils.getNowDate());
        history.setCreateTime(DateUtils.getNowDate());
        notifyHistoryMapper.insertNotifyHistory(history);
        return Mono.empty();
    }


}
